from flask import render_template, url_for, flash, redirect, session
from flask_paginate import Pagination, get_page_parameter
from app_db import *
from ..model.base_opera import *
from ..forms import LoginForm, RegisterForm, AccountForm
from config import config
from src.utils.date_translate import from_str_to_date
import json


# db init
@app.before_first_request
def create_db():
    # db init
    db.create_all()
    db.session.commit()


# 登陆
@app.route('/')
def p_index():
    return redirect(url_for('login'))


@app.route('/index')
def l_index():
    return redirect(url_for('login'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    if session.get('name'):
        flash(message='已登录')
        return redirect(url_for('index_info'))
    form = LoginForm()
    if form.validate_on_submit():
        user = UserInfo.query.filter_by(name=form.name.data).first()
        if user and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            next_url = request.args.get('next').replace('/', '') if request.args.get('next') else 'index_info'
            # print('next_url: {}'.format(next_url))
            session['id'] = user.id
            session['name'] = user.name

            user_id = user.id

            flash(message='登陆成功!')
            return redirect(url_for(next_url))
        else:
            flash(message='用户或密码错误')
            return redirect(url_for('login'))

    return render_template('login.html', form=form)


# 登出
@app.route('/logout')
@login_required
def logout():
    logout_user()
    session.clear()
    flash(message='您已退出')
    return redirect(url_for('login'))


# 注册
@app.route('/reg', methods=['GET', 'POST'])
def register():
    form = RegisterForm()

    if form.validate_on_submit():
        user = UserInfo.query.filter_by(name=form.name.data).first()
        if user:
            flash(message="用户已存在")
            return redirect(url_for('register'))

        user_password = UserInfo()
        user_password.password(password=form.password.data)

        json_data = {
            'name': form.name.data,
            'password_hash': user_password.password_hash
        }
        opera_user.post(requst_json=json_data)
        flash(message='注册成功')
        return redirect(url_for('login'))
    return render_template('register.html', form=form)


# index 录入
@app.route('/index_info', methods=['GET', 'POST'])
@login_required
def index_info():
    user_id = session['id']
    if request.method == 'POST':
        date = request.form.get('date')
        money = request.form.get('money')
        income_expense_class_id = request.form.get('income_expense_class_id')
        income_expense_id = request.form.get('income_expense_id')
        income_expense_type_id = request.form.get('income_expense_type_id')
        pay_channel_id = request.form.get('pay_channel_id')
        account_class_id = request.form.get('account_class_id')
        account_id = request.form.get('account_id')
        remark = request.form.get('remark')

        if not income_expense_class_id or not income_expense_id or not account_class_id or not account_id:
            flash(message='参数不完整，请补充完整')
            return render_template('parameter_err.html')

        if opera_account_info.get(user_id, date, money, income_expense_id, account_id):
            flash(message='数据已存在')
        else:
            post_data = {
                'date': date,
                'money': money,
                'income_expense_class_id': income_expense_class_id,
                'income_expense_id': income_expense_id,
                'income_expense_type_id': income_expense_type_id,
                'pay_channel_id': pay_channel_id,
                'account_class_id': account_class_id,
                'account_id': account_id,
                'remark': remark,
                'user_id': user_id
            }
            opera_account_info.post(json_data=post_data)
            flash('提交成功！')

        return redirect(url_for('index_info'))

    json_data = []
    page = request.args.get(get_page_parameter(), type=int, default=1)
    all_data = read_account_info(user_id=user_id).first()
    if all_data:
        datas = read_account_info(user_id=user_id).paginate(page, per_page=config.PER_PAGE_NUMBER, error_out=False)
        for info in datas.items:
            mid_json = {
                'date': info[1],
                'money': info[2],
                'income_expense_type_id': info[3],
                'type_name': '{}-{}'.format(info[8], info[4]),
                'account_name': '{}-{}-{}'.format(info[9], info[7], info[5]),
                'remark': info[6],
                'id': info[10]
            }
            json_data.append(mid_json)        

    # 收支一级类别
    income_expense_class_json = read_model_income_expense_class()

    # 支付方式
    pay_channel_json = read_model_common_code(category_code='pay_channel')


    # 账户类别
    account_class_json = read_model_common_code(category_code='account_type')

    return render_template('index.html', json_data=json_data, account_class_json=account_class_json, pay_channel_json=pay_channel_json,
                           income_expense_class_json=income_expense_class_json, user_id=user_id)


# index 录入退款
@app.route('/index_info_refund', methods=['GET'])
@login_required
def index_info_refund():
    id = int(request.args.get('id')) if request.args.get('id') else None
    print('id: {}'.format(id))
    if id:
        opera_account_info.update(id)

    return redirect(url_for('index_info'))


# 账户管理
@app.route('/account_manager', methods=['GET', 'POST'])
@login_required
def account_manager():
    user_id = session['id']
    if request.method == 'POST':
        request_data = request.form.to_dict()

        account_name = request_data.get('account_name')
        type_id = int(request_data.get('type_id')) if request_data.get('type_id') and len(request_data.get('type_id')) > 0 else None

        if account_name and type_id:
            if AccountType.query.filter_by(type_id=type_id).filter_by(account_name=account_name).\
                    filter_by(user_id=user_id).filter_by(is_valid=1).first():
                flash(message='数据已存在')
            else:
                task = AccountType(type_id=type_id, account_name=account_name, user_id=user_id, is_valid=1)
                db.session.add(task)
                db.session.commit()

    json_data = read_model_account_type(user_id=user_id)
    account_type_json = read_model_common_code(category_code='account_type', id=3)
    return render_template('account_manager.html', json_data=json_data, account_type_json=account_type_json)


# 历史数据查询
@app.route('/history_query', methods=['GET', 'POST'])
@login_required
def history_query():
    user_id = session['id']

    # 收支一级类别
    income_expense_class_json = read_model_income_expense_class()

    # 支付方式
    pay_channel_json = read_model_common_code(category_code='pay_channel')

    # 账户类别
    account_class_json = read_model_common_code(category_code='account_type')

    if request.method == 'POST':
        date_type = int(request.form.get('date_type')) if request.form.get('date_type') and len(request.form.get('date_type')) > 0 else None
        date = request.form.get('date')
        income_expense_class_id = int(request.form.get('income_expense_class_id')) if request.form.get('income_expense_class_id') and len(request.form.get('income_expense_class_id')) > 0 else None
        income_expense_id = int(request.form.get('income_expense_id')) if request.form.get(
            'income_expense_id') and len(request.form.get('income_expense_id')) > 0 else None
        income_expense_type_id = int(request.form.get('income_expense_type_id')) if request.form.get(
            'income_expense_type_id') and len(request.form.get('income_expense_type_id')) > 0 else None
        pay_channel_id = int(request.form.get('pay_channel_id')) if request.form.get('pay_channel_id') and len(request.form.get('pay_channel_id')) > 0 else None
        account_class_id = int(request.form.get('account_class_id')) if request.form.get('account_class_id') and len(request.form.get('account_class_id')) > 0 else None
        account_id = int(request.form.get('account_id')) if request.form.get('account_id') and len(request.form.get('account_id')) > 0 else None

        income_expense_class_id = None if income_expense_class_id == -1 else income_expense_class_id
        account_class_id = None if account_class_id == -1 else account_class_id
        pay_channel_id = None if pay_channel_id == -1 else pay_channel_id
        json_data = []
        page = request.args.get(get_page_parameter(), type=int, default=1)
        query = read_account_history(user_id=user_id, date=date, date_type=date_type, income_expense_id=income_expense_id, 
                                        income_expense_class_id=income_expense_class_id,pay_channel_id=pay_channel_id,
                                        income_expense_type_id=income_expense_type_id, account_class_id=account_class_id, account_id=account_id)
                                        
        all_data = query.first()

        if all_data:
            datas = query.paginate(page, per_page=config.PER_PAGE_NUMBER, error_out=False)
            for info in datas.items:
                mid_json = {
                    'date': info[1],
                    'money': info[2],
                    'income_expense_type_id': info[3],
                    'type_name': '{}-{}'.format(info[8], info[4]),
                    'account_name': '{}-{}-{}'.format(info[9], info[7], info[5]),
                    'remark': info[6],
                    'id': info[10]
                }
                json_data.append(mid_json)

        return render_template('history_account.html', json_data=json_data, account_class_json=account_class_json,user_id=user_id,
                               income_expense_class_json=income_expense_class_json, pay_channel_json=pay_channel_json)

    return render_template('history_account.html', json_data=[], account_class_json=account_class_json,user_id=user_id,
                           income_expense_class_json=income_expense_class_json, pay_channel_json=pay_channel_json)


# 历史数据查询退款
@app.route('/history_query_refund', methods=['GET'])
@login_required
def history_query_refund():
    id = int(request.args.get('id')) if request.args.get('id') else None
    if id:
        opera_account_info.update(id)

    return redirect(url_for('history_query'))


# 信用卡还款金额趋势
@app.route('/repayment_recenty_info', methods=['GET', 'POST'])
def repayment_recenty_info():
    user_id = session['id']
    # 账户
    query_info = AccountType.query.filter_by(type_id=1).filter_by(user_id=user_id).filter_by(is_valid=1).all()
    account_json = [{
        'id': info.id,
        'account_name': info.account_name
    } for info in query_info]
    # 年份
    year_begin = 2019
    years_json = [year_begin + i for i in range(50)]
    # 月份
    month_begin = 1
    months_json = [month_begin + i for i in range(12)]
    if request.method == 'POST':
        account_id = int(request.form.get('account_id'))
        begin_year = int(request.form.get('begin_year'))
        begin_month = int(request.form.get('begin_month'))
        end_year = int(request.form.get('end_year'))
        end_month = int(request.form.get('end_month'))

        account_id = None if account_id == -1 else account_id
        begin_year = None if begin_year == -1 else begin_year
        begin_month = None if begin_month == -1 else begin_month
        end_year = None if end_year == -1 else end_year
        end_month = None if end_month == -1 else end_month

        #  还款结果
        json_data = repayment_recenty(user_id, account_id=account_id, begin_year=begin_year, begin_month=begin_month,
                                      end_year=end_year, end_month=end_month)

        account_id = -1 if not account_id else account_id
        begin_year = -1 if not begin_year else begin_year
        begin_month = -1 if not begin_month else begin_month
        end_year = -1 if not end_year else end_year
        end_month = -1 if not end_month else end_month

        return render_template('repayment_recenty.html', json_data=json_data, account_json=account_json,
                               years_json=years_json, months_json=months_json,
                               account_id=account_id,
                               begin_year=begin_year,
                               begin_month=begin_month,
                               end_year=end_year,
                               end_month=end_month,
                               user_id=user_id)

    #  还款结果
    json_data = repayment_recenty(user_id)
    return render_template('repayment_recenty.html', json_data=json_data, account_json=account_json,
                           years_json=years_json, months_json=months_json,
                           account_id=-1,
                           begin_year=-1,
                           begin_month=-1,
                           end_year=-1,
                           end_month=-1,
                           user_id=user_id
                           )


#  剔除信用卡还款后的消费趋势与构成
@app.route('/cost_recenty_info', methods=['GET', 'POST'])
def cost_recenty_info():
    user_id = session['id']

    # 收支一级类别
    income_expense_class_json = read_model_income_expense_class()

    # 支付方式
    pay_channel_json = read_model_common_code(category_code='pay_channel')

    # 账户类别
    account_class_json = read_model_common_code(category_code='account_type')

    # 年份
    year_begin = 2019
    years_json = [year_begin + i for i in range(50)]
    # 月份
    month_begin = 1
    months_json = [month_begin + i for i in range(12)]
    # 日
    day_begin = 1
    days_json = [day_begin + i for i in range(31)]

    if request.method == 'POST':
        income_expense_class_id = int(request.form.get('income_expense_class_id')) if request.form.get('income_expense_class_id') else None
        income_expense_id = int(request.form.get('income_expense_id')) if request.form.get('income_expense_id') else None
        pay_channel_id = int(request.form.get('pay_channel_id')) if request.form.get('pay_channel_id') else None
        account_class_id = int(request.form.get('account_class_id')) if request.form.get('account_class_id') else None
        account_id = int(request.form.get('account_id')) if request.form.get('account_id') else None
        begin_year = int(request.form.get('begin_year')) if request.form.get('begin_year') else None
        begin_month = int(request.form.get('begin_month')) if request.form.get('begin_month') else None
        begin_day = int(request.form.get('begin_day')) if request.form.get('begin_day') else None
        end_year = int(request.form.get('end_year')) if request.form.get('end_year') else None
        end_month = int(request.form.get('end_month')) if request.form.get('end_month') else None
        end_day = int(request.form.get('end_day')) if request.form.get('end_day') else None

        income_expense_class_id = None if income_expense_class_id == -1 else income_expense_class_id
        income_expense_id = None if income_expense_id == -1 else income_expense_id
        pay_channel_id = None if pay_channel_id == -1 else pay_channel_id
        account_class_id = None if account_class_id == -1 else account_class_id
        account_id = None if account_id == -1 else account_id
        begin_year = None if begin_year == -1 else begin_year
        begin_month = None if begin_month == -1 else begin_month
        begin_day = None if begin_day == -1 else begin_day
        end_year = None if end_year == -1 else end_year
        end_month = None if end_month == -1 else end_month
        end_day = None if end_day == -1 else end_day

        json_data = cost_recenty(user_id, income_expense_class_id=income_expense_class_id,
                                 income_expense_id=income_expense_id, pay_channel_id=pay_channel_id,
                                 account_class_id=account_class_id, account_id=account_id, begin_year=begin_year,
                                 begin_month=begin_month, begin_day=begin_day, end_year=end_year,
                                 end_month=end_month, end_day=end_day)
        if not json_data:
            flash(message='参数不规范')

        income_expense_class_id = -1 if not income_expense_class_id else income_expense_class_id
        income_expense_id = -1 if not income_expense_id else income_expense_id
        pay_channel_id = -1 if not pay_channel_id else pay_channel_id
        account_class_id = -1 if not account_class_id else account_class_id
        account_id = -1 if not account_id else account_id
        begin_year = -1 if not begin_year else begin_year
        begin_month = -1 if not begin_month else begin_month
        begin_day = -1 if not begin_day else begin_day
        end_year = -1 if not end_year else end_year
        end_month = -1 if not end_month else end_month
        end_day = -1 if not end_day else end_day

        category_json_data = cost_recenty_struct_class(user_id=user_id,pay_channel_id=pay_channel_id,
                 account_class_id=account_class_id, account_id=account_id, begin_year=begin_year,
                                                       begin_month=begin_month, begin_day=begin_day,
                 end_year=end_year, end_month=end_month, end_day=end_day)

        return render_template('cost_recenty.html', json_data=json_data, user_id=user_id,
                               income_expense_class_json=income_expense_class_json, pay_channel_json=pay_channel_json,
                               account_class_json=account_class_json, category_json_data=category_json_data,
                               years_json=years_json, months_json=months_json, days_json=days_json,
                               income_expense_class_id=income_expense_class_id,
                               income_expense_id=income_expense_id,
                               pay_channel_id=pay_channel_id,
                               account_class_id=account_class_id,
                               account_id=account_id,
                               begin_year=begin_year,
                               begin_month=begin_month,
                               begin_day=begin_day,
                               end_year=end_year,
                               end_month=end_month,
                               end_day=end_day)

    json_data = cost_recenty(user_id)
    category_json_data = cost_recenty_struct_class(user_id=user_id)
    return render_template('cost_recenty.html', json_data=json_data, user_id=user_id,
                           income_expense_class_json=income_expense_class_json, pay_channel_json=pay_channel_json,
                           account_class_json=account_class_json, category_json_data=category_json_data,
                           years_json=years_json, months_json=months_json, days_json=days_json,
                           income_expense_class_id=-1,
                           income_expense_id=-1,
                           pay_channel_id=-1,
                           account_class_id=-1,
                           account_id=-1,
                           begin_year=-1,
                           begin_month=-1,
                           begin_day=-1,
                           end_year=-1,
                           end_month=-1,
                           end_day=-1
                           )
